package com.example.demo.ai.qwen;

import cn.hutool.ai.core.AIConfig;
import cn.hutool.ai.core.AIService;
import cn.hutool.ai.core.BaseAIService;
import cn.hutool.ai.core.Message;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName QwenService
 * @Description:
 * @Author: hgq
 * @CreateDate: 2025/5/13 16:39
 * @UpdateUser: hgq
 * @UpdateDate: 2025/5/13 16:39
 * @UpdateRemark:
 * @Version: 1.0
 */
public class QwenServiceImpl extends BaseAIService implements AIService {

    //对话补全
    private final String CHAT_ENDPOINT = "/chat/completions";

    public QwenServiceImpl(AIConfig config) {
        super(config);
    }

    @Override
    public String chat(String prompt) {
        List<Message> messages = new ArrayList();
        messages.add(new Message("system", "你是我的好伙伴"));
        messages.add(new Message("user", prompt));
        return this.chat(messages);
    }

    @Override
    public String chat(List<Message> messages) {
        String paramJson = this.buildChatRequestBody(messages);
        HttpResponse response = this.sendPost(CHAT_ENDPOINT, paramJson);
        return response.body();
    }

    private String buildChatRequestBody(List<Message> messages) {
        Map<String, Object> paramMap = new HashMap();
        paramMap.put("model", this.config.getModel());
        paramMap.put("messages", messages);
        paramMap.put("stream", true); // 流式输出
        paramMap.putAll(this.config.getAdditionalConfigMap());
        return JSONUtil.toJsonStr(paramMap);
    }

    private String buildBetaRequestBody(String prompt) {
        Map<String, Object> paramMap = new HashMap();
        paramMap.put("model", this.config.getModel());
        paramMap.put("prompt", prompt);
        paramMap.putAll(this.config.getAdditionalConfigMap());
        return JSONUtil.toJsonStr(paramMap);
    }
}
